package com.chenyue.cm.user.controller;


import com.alibaba.fastjson.JSON;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.base.bean.PageVo;
import com.chenyue.cm.base.bean.Pageable;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.utils.RequestUtil;
import com.chenyue.cm.common.utils.StringUtils;
import com.chenyue.cm.moudules.system.utils.ShiroUtils;
import com.chenyue.cm.user.domain.JdAttrValue;
import com.chenyue.cm.user.domain.JdGoodsSpu;
import com.chenyue.cm.user.service.JdAttrKeyService;
import com.chenyue.cm.user.domain.JdAttrKey;
import com.chenyue.cm.user.domain.JdAttrKeyExample;
import com.chenyue.cm.user.service.JdAttrValueService;
import com.chenyue.cm.user.service.JdGoodsSkuService;
import com.chenyue.cm.user.service.JdGoodsSpuService;
import com.chenyue.cm.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
* @author chenyue-cm
* @date 2024-03-13
*/
@RestController
@RequestMapping("/jdAttrKey")
public class JdAttrKeyController {

    @Autowired
    private JdAttrKeyService mAttrKeyService;

    @Autowired
    private JdAttrValueService mAttrValueService;

    @Autowired
    private JdGoodsSkuService mGoodsSkuService;

    @Autowired
    private JdGoodsSpuService mGoodsSpuService;

    @RequestMapping("/getList")
    @ResponseBody
    @Log(value="获取商品sku属性列表",type="2",module="2")
    public Success<PageVo<JdAttrKey>> getList(HttpServletRequest request, HttpServletResponse response) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        PageVo<JdAttrKey> result = mAttrKeyService.getPageBean(pageInfo, JdAttrKey.class);
        return Success.success(result);
    }


    /**
     * @param vo
     * @param request
     * @param response
     * @param model
     * @return
     */
    @Log(value="保存商品sku属性",type="2",module="2")
    @RequestMapping("/save")
    @ResponseBody
    public Success save(JdAttrKey vo, HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");

        if (id != null && id != "") {
            vo.setUpdateTime(DateUtils.getTimeNow());
            vo.setUpdateUser(ShiroUtils.getUserId());
            mAttrKeyService.getBaseMapper().updateById(vo);
        } else {
            vo.setId(UUID.randomUUID().toString().replace("-", ""));
            vo.setCreateTime(DateUtils.getTimeNow());
            vo.setCreateUser(ShiroUtils.getUserId());
            mAttrKeyService.save(vo);
        }

        return Success.success();
    }


    /**
     * @param id
     * @param request
     * @param response
     * @return
     */
    @Log(value="根据id删除商品sku属性",type="2",module="2")
    @RequestMapping("/delete/{id}")
    @ResponseBody
    public Success delete(@PathVariable String id, HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");
        JdAttrKeyExample aExample = new JdAttrKeyExample();
        aExample.createCriteria().andIdEqualTo(id);
        mAttrKeyService.deleteByExample(aExample);

        return Success.success();
    }

    /**
     * 【API】----  删除多个数据
     *
     * @param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    @Log(value="商品sku属性-删除多个数据",type="2",module="2")
    public Success delete(HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");
        String ids = request.getParameter("ids");
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            mAttrKeyService.deleteByPrimaryKey(idString);
        }
        return Success.success();
    }

    @RequestMapping("/getAttrKeyListByClassifyId")
    @ResponseBody
    public Success getAttrKeyListByClassifyId(String classify,String goodsId) {
        JdAttrKeyExample aExample = new JdAttrKeyExample();
        aExample.createCriteria().andClassifyIdEqualTo(classify);
        List<JdAttrKey> mAttrKeys = mAttrKeyService.selectByExample(aExample);  //通过分类id找出所有key

        List<String> keyIds = new ArrayList<>();
        List<JdAttrValue> mAttrValueByKeyIds = null;
        List<Map<String, Object>> mapList = null;
        if(mAttrKeys.size() > 0){
            mAttrKeys.stream().forEach(JdAttrKey -> {
                keyIds.add(JdAttrKey.getId());
            });
            mAttrValueByKeyIds = mAttrValueService.getMAttrValueByKeyIds(keyIds); //通过key找出所有values
            Set<String> setSku = mGoodsSkuService.getVauleIds(goodsId); //获取sku 所保存values

            mapList = new ArrayList<>();
            for (JdAttrKey JdAttrKey : mAttrKeys) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", JdAttrKey.getId());
                map.put("attrName", JdAttrKey.getAttrName());
                if (setSku != null && setSku.size() > 0) {
                    List<String> checkIds = new ArrayList<>();
                    for (JdAttrValue mAttrValueByKeyId : mAttrValueByKeyIds) {
                        if (JdAttrKey.getId().equals(mAttrValueByKeyId.getKeyId()) && setSku.contains(mAttrValueByKeyId.getId())) {
                            checkIds.add(mAttrValueByKeyId.getId());
                        }
                    }
                    map.put("values", checkIds);
                } else {
                    map.put("values", new ArrayList<>());
                }
                mapList.add(map);
            }
        }

        return Success.success(mapList);
    }


    /**
     * 【API】----  获取商品属性信息
     *
     * @param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/getAttrListByGoodsId")
    @ResponseBody
    @Log(value="获取商品attrList",type="2",module="2")
    public Success getAttrListByGoodsId(HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");

        String classify = request.getParameter("classify");
        String goodsId = request.getParameter("goodsId");


        List<Map<String, Object>> mapList = new ArrayList<>();

        JdGoodsSpu a = mGoodsSpuService.selectByPrimaryKey(goodsId);
        String  attrInfo = a.getUpdateUser();
        if(!StringUtils.isBlank(attrInfo)){
            mapList = JSON.parseObject( a.getUpdateUser() ,List.class );
            return Success.success(mapList);
        }

        //通过分类id找出所有key
        JdAttrKeyExample aExample = new JdAttrKeyExample();
        aExample.createCriteria().andClassifyIdEqualTo(classify);
        List<JdAttrKey> mAttrKeys = mAttrKeyService.selectByExample(aExample);

        Set<String> setSku = mGoodsSkuService.getVauleIds(goodsId); //获取sku 所保存values

        for (JdAttrKey JdAttrKey : mAttrKeys) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", JdAttrKey.getId());
            map.put("attrName", JdAttrKey.getAttrName());

            //通过key找出所有attrValueList
            List<JdAttrValue> mAttrValueList = mAttrValueService.getAttrValueList(JdAttrKey.getId());
            List<String> attrList = new ArrayList<>();
            for (JdAttrValue mAttrValue : mAttrValueList) {
                attrList.add( mAttrValue.getValue() );
            }
            map.put("itemList", attrList );

            List<String> checkedAttrList = new ArrayList<>();
            // checkedAttrList.add( mAttrValueList.get(0).getValue() ) ;
            map.put("values", checkedAttrList );

            mapList.add(map);
        }
        return Success.success(mapList);

    }


}
